#include "rpc_servicemgr.h"

RPCServiceMgr::RPCServiceMgr( RPCSysMgr * rpcsysmgr )
    : m_rpcsysmgr( rpcsysmgr )
{}

RPCServiceMgr::~RPCServiceMgr() throw()
{}

int32_t RPCServiceMgr::module_init()
{
    m_servicesmap.clear();
    LOG_STREAM_INFO << "module[" << module_name() << "] initialize!" << LOG_EOM;
    return 0;
}

void RPCServiceMgr::module_fini()
{
    for( SERVICES_MAP::iterator iter = m_servicesmap.begin(); iter != m_servicesmap.end(); ++iter )
    {
        LOG_STREAM_INFO << "service[" << iter->first << "] skel unregister successed" << LOG_EOM;
        google::protobuf::Service * service = iter->second;
        delete service;
    }
    m_servicesmap.clear();
    LOG_STREAM_INFO << "module[" << module_name() << "] finalize!" << LOG_EOM;
    return;
}

const char * RPCServiceMgr::module_name() const
{
    static const std::string name = "RPCServiceMgr";
    return name.c_str();
}

::google::protobuf::Service* RPCServiceMgr::get_service( const std::string & service_fullname )
{
    Guard<Thread_Mutex> lock( m_mutex );
    SERVICES_MAP::iterator iter;
    if( m_servicesmap.end() != ( iter = m_servicesmap.find( service_fullname ) ) )
        return iter->second;
    return NULL;
}

int32_t RPCServiceMgr::reg_service( const std::string service_fullname,
    ::google::protobuf::Service * service )
{
    if( NULL == service )
    {
        LOG_STREAM_ERROR << "service[" << service_fullname << "] object is null" << LOG_EOM;
        return -1;
    }

    if( !m_servicesmap.insert( SERVICES_MAP::value_type( service_fullname, service ) ).second )
    {
        LOG_STREAM_ERROR << "service[" << service_fullname << "] is already register" << LOG_EOM;
        return -1;
    }
    LOG_STREAM_INFO << "service[" << service_fullname << "] skel register successed" << LOG_EOM;
    return 0;
}


